package com.nercel.dsj.gksales.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nercel.dsj.gksales.dao.mapper.PaymentMapper;
import com.nercel.dsj.gksales.model.ListResult;
import com.nercel.dsj.gksales.model.PayServiceType;
import com.nercel.dsj.gksales.model.PayType;
import com.nercel.dsj.gksales.model.QueryParams;
import com.nercel.dsj.gksales.model.dto.PaymentResultDTO;
import com.nercel.dsj.gksales.model.entity.Payment;
import com.nercel.dsj.gksales.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author sunlin
 * @date 2019-4-1
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PaymentServiceImpl implements PaymentService {

	private final PaymentMapper paymentMapper;

	@Override
	public PaymentResultDTO findById(Integer id) {
		return paymentMapper.selectByPrimaryKey(id);
	}

	@Override
	public void save(Payment payment) {
		paymentMapper.insertSelective(payment);
	}

	@Override
	public void update(Payment payment) {
		paymentMapper.updateByPrimaryKeySelective(payment);
	}

	@Override
	public void delete(Integer id) {
		paymentMapper.deleteByPrimaryKey(id);
	}

	@Override
	public List<Payment> listAll() {
		return null;
	}

	@Override
	public ListResult<PaymentResultDTO> listWithPaging(QueryParams queryParams) {
		Page<PaymentResultDTO> page = PageHelper.startPage(queryParams.getPageNumber(), queryParams.getPageSize());
		paymentMapper.query(queryParams);
		return new ListResult<>(page);
	}

	@Override
	public Payment findByOrderNumber(String orderNumber) {
		return paymentMapper.findByOrderNumber(orderNumber);
	}


	@Override
	public void savePayment(String orderNumber, Double totalAmount, Integer count,
							Integer userId, PayType payType, PayServiceType payServiceType, String data) {
		//记录支付订单数据
		Double amount = totalAmount*100;//db存储按分为单位，支付宝按元为单位
		Payment payment = new Payment();
		payment.setOrderNumber(orderNumber);
		payment.setSuccessful(false);
		payment.setAmount(amount.intValue());
		payment.setCount(count);
		payment.setCreatedTime(new Date());
		payment.setType(payType);
		payment.setUserId(userId);
		payment.setData(data);
		payment.setServiceType(payServiceType);
		save(payment);
	}
}
